<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: application_top.php 357 2013-11-04 15:32:21Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 357 $
* 	zuletzt geaendert von:	$Author: siekiera $
* 	Datum:					$Date: 2013-11-04 15:32:21 +0000 (Mon, 04 Nov 2013) $
*
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
*
* 	Copyright (c) since 2011 SEO:mercari
* --------------------------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     nextcommerce - www.nextcommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */

define('PAGE_PARSE_START_TIME', microtime());

error_reporting(E_ALL & ~E_NOTICE);
#error_reporting(E_ALL & ~E_WARNING);

if(!ini_get('display_errors'))
    ini_set('display_errors', 1);

if (!defined('HTTP_SERVER')) {
  if(file_exists('includes/local/configure.php') && filesize('includes/local/configure.php') > 0)
  	include('includes/local/configure.php');
  elseif(file_exists('includes/configure.php') && filesize('includes/configure.php') > 0)
  	include('includes/configure.php');
  elseif(!defined('MERCARI_INSTALLED')) {
  	header('Location: installer/');
	exit;
  } 
  else {
  	header('Location: installer/');
  	exit;
  }
}

@date_default_timezone_set('Europe/Berlin');

$request_type = (getenv('HTTPS') == '1' || getenv('HTTPS') == 'on' || !empty($_SERVER['HTTP_X_FORWARDED_HOST'])) ? 'SSL' : 'NONSSL';

if(empty($PHP_SELF))
	$PHP_SELF = basename($_SERVER['PHP_SELF']);

include(DIR_WS_INCLUDES.'filenames.php');
include(DIR_WS_INCLUDES.'database_tables.php');
include(DIR_WS_CLASSES.'console.php');

define('SQL_CACHEDIR', DIR_FS_CATALOG.'cache/');

function auto_loader($classname) {
	try {
		if (!preg_match('=^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$=m',$classname))
			throw new Exception('Klasse '.$classname.' ist ungültig');
		
		$fname = DIR_WS_CLASSES.'class.'.strtolower($classname).'.php';
		
		if (!file_exists($fname))
			throw new Exception($fname.' konnte nicht gefunden werden');
		
		require_once($fname);

		if (!class_exists($classname))
			throw new Exception('Datei '.$fname.' enthält keine Klasse '.$classname);
		
		return true;
	} catch(Exception $e) {}
}
spl_autoload_register('auto_loader');

$db = new mercari_db();

$configuration = $db->db_query("SELECT configuration_key, configuration_value FROM ".TABLE_CONFIGURATION." WHERE configuration_key != 'CURRENT_TEMPLATE'");
while(!$configuration->EOF) {
	define($configuration->fields['configuration_key'], $configuration->fields['configuration_value']);
	$configuration->MoveNext();
}
include(DIR_WS_INCLUDES.'functions.php');
require(DIR_WS_CLASSES.'class.page_break.php');

$http_domain = get_top_level_domain(HTTP_SERVER);
$https_domain = get_top_level_domain(HTTPS_SERVER);
$current_domain = (($request_type == 'NONSSL') ? $http_domain : $https_domain);

$SESS_LIFE = (SESSION_EXPIRE_TIME*60);

$session = new sessions();

if(function_exists('session_set_cookie_params')) {
	session_set_cookie_params(0, DIR_WS_CATALOG, (not_null($current_domain) ? '.'.$current_domain : ''));

} elseif (function_exists('ini_set')) {
	ini_set('session.cookie_lifetime', '0');
	ini_set('session.cookie_path', DIR_WS_CATALOG);
	ini_set('session.cookie_domain', (not_null($current_domain) ? '.'.$current_domain : ''));
}

if(isset($_COOKIE[session_name()]))
	session_id($_COOKIE[session_name()]);

$session_started = false;
if((GZIP_COMPRESSION == 'true') && ($ext_zlib_loaded = extension_loaded('zlib'))) {
	if (($ini_zlib_output_compression = (int)ini_get('zlib.output_compression')) < 1)
		ob_start('ob_gzhandler');
	else
		ini_set('zlib.output_compression_level', GZIP_LEVEL);
} else
	ob_start();

if(SESSION_FORCE_COOKIE_USE == 'true') {
	setcookie('cookie_test', 'please_accept_for_session', time() + 60 * 60 * 24 * 30, DIR_WS_CATALOG, $current_domain);
	if (isset($_COOKIE['cookie_test'])) {
		$session->_sess_start();
		include (DIR_WS_FUNCTIONS.'tracking.php');
		$session_started = true;
	}

} else {
	$session->_sess_start();
	include (DIR_WS_FUNCTIONS.'tracking.php');
	$session_started = true;
}
if(!$session->_sess_check() && !empty($_SESSION['customer_id'])) {
	session_destroy();
	redirect(href_link(FILENAME_LOGIN));
}

$truncate_session_id = false;
if(check_agent()) {
	$truncate_session_id = true;
	if (strpos($_SERVER['REQUEST_URI'], session_name())) {
		$location = href_link(basename($_SERVER['SCRIPT_NAME']) , get_all_get_params(array(session_name())) , $request_type, false);
		header("HTTP/1.1 301 Moved Permanently");
		redirect($location);
	}
}

require_once(DIR_WS_CLASSES.'class.phpmailer.php');
if(EMAIL_TRANSPORT == 'smtp')
	require_once(DIR_WS_CLASSES.'class.smtp.php');

function CacheCheck() {
	if(USE_CACHE == 'false')
		return false;
	if(!isset($_COOKIE['mercari']))
		return false;
	return true;
}

$InputFilter = new input_filter();

$_GET = $InputFilter->process(str_replace('<>','',$_GET));
$_POST = $InputFilter->process(str_replace('<>','',$_POST));
$_REQUEST = $InputFilter->process(str_replace('<>','',$_REQUEST));
$_GET = $InputFilter->safeSQL($_GET);
$_POST = $InputFilter->safeSQL($_POST); 
$_REQUEST = $InputFilter->safeSQL($_REQUEST);

$http_domain = get_top_level_domain(HTTP_SERVER);
$https_domain = get_top_level_domain(HTTPS_SERVER);
$current_domain = (($request_type == 'NONSSL') ? $http_domain : $https_domain);

$current_script = basename(basename($_SERVER['SCRIPT_FILENAME']));

if(MODULE_SEO_URL_INDEX_AVOIDDUPLICATECONTENT=='True' && 
	MODULE_SEO_URL_INDEX_STATUS=='True' && 
	($current_script==FILENAME_DEFAULT || 
	$current_script==FILENAME_PRODUCT_INFO || 
	$current_script==FILENAME_CONTENT || 
	substr_count($_SERVER['REQUEST_URI'], 'seo_url.php') > 0 )
	) {

	if(substr_count($_SERVER['REQUEST_URI'],'seo_url.php') > 0 ) {
		if($_GET['products_id'] != '')
			$current_script = 'product_info.php';
		elseif ($_GET['cPath'] != '')
			$current_script = 'index.php';
		elseif ($_GET['coID'] != '')
			$current_script = 'shop_content.php';
		elseif ($_GET['blog_item'] != '' )
			$current_script = 'blog.php';
		elseif ($_GET['blog_cat'] != '' )
			$current_script = 'blog.php';
	}

	require_once(DIR_FS_INC.'inc.seo_url.php');
	!$seo_url ? $seo_url = new SeoUrl() : false;

	$redirectElementId = $seo_url->getIdForXTCSumaFriendlyURL($current_script);
}

if(($data->fields['language_id'] != $_SESSION['languages_id']) && !empty($data->fields['language_id']) && !isset($_GET['language'])) {
	$languageId = $db->db_query("SELECT code FROM ".TABLE_LANGUAGES." WHERE languages_id='".$data->fields['language_id']."'", true);
	$_GET['language'] = $languageId->fields['code'];
}

if (SESSION_CHECK_IP_ADDRESS == 'True') {
	$ip_address = get_ip_address();
	if (!isset ($_SESSION['SESSION_IP_ADDRESS']))
		$_SESSION['SESSION_IP_ADDRESS'] = $ip_address;

	if ($_SESSION['SESSION_IP_ADDRESS'] != $ip_address) {
		session_destroy();
		redirect(href_link(FILENAME_LOGIN));
	}
}

if (!isset($_SESSION['language']) || isset ($_GET['language'])) {
	$lng = new language(input_validation($_GET['language'], 'char', ''));

	if(!isset($_GET['language']))
		$lng->get_browser_language();

	$_SESSION['language'] = $lng->language['directory'];
	$_SESSION['languages_id'] = $lng->language['id'];
	$_SESSION['language_charset'] = $lng->language['language_charset'];
	$_SESSION['language_code'] = $lng->language['code'];
}

if (isset($_SESSION['language']) && !isset($_SESSION['language_charset'])) {
	$lng = new language(input_validation($_SESSION['language'], 'char', ''));

	$_SESSION['language'] = $lng->language['directory'];
	$_SESSION['languages_id'] = $lng->language['id'];
	$_SESSION['language_charset'] = $lng->language['language_charset'];
	$_SESSION['language_code'] = $lng->language['code'];
}

require(DIR_WS_LANGUAGES.$_SESSION['language'].'/'.$_SESSION['language'].'.php');

$define_link = $db->db_query("SELECT
									cp.url_text AS url, cn.file_name AS file_name, cn.file_name_php AS php
								FROM
									".TABLE_SEO_URL_NAMES." AS cn
									LEFT OUTER JOIN
										".TABLE_SEO_URL_PERSONAL_LINKS." AS cp ON (cp.file_name = cn.file_name AND cp.language_id = '".$_SESSION['languages_id']."')", true);
while(!$define_link->EOF) {
	define(strtoupper($define_link->fields['file_name']), (MODULE_SEO_URL_INDEX_STATUS=='True' ? ($define_link->fields['url']!='' ? $define_link->fields['url'].'.html' : $define_link->fields['php']) : $define_link->fields['php']) );
	$define_link->MoveNext();
}
if (!isset ($_SESSION['currency']) || isset ($_GET['currency']) || ((USE_DEFAULT_LANGUAGE_CURRENCY == 'true') && (LANGUAGE_CURRENCY != $_SESSION['currency']))) {
	if (isset ($_GET['currency'])) {
		if (!$_SESSION['currency'] = currency_exists($_GET['currency']))
			$_SESSION['currency'] = (USE_DEFAULT_LANGUAGE_CURRENCY == 'true') ? LANGUAGE_CURRENCY : DEFAULT_CURRENCY;
	} else
		$_SESSION['currency'] = (USE_DEFAULT_LANGUAGE_CURRENCY == 'true') ? LANGUAGE_CURRENCY : DEFAULT_CURRENCY;

}
if(isset($_SESSION['currency']) && $_SESSION['currency'] == '')
	$_SESSION['currency'] = DEFAULT_CURRENCY;

require(DIR_WS_INCLUDES.'write_customers_status.php');
$main = new main();

$price = new price($_SESSION['currency'], $_SESSION['customers_status']['customers_status_id']);

$schema = new microdata();

if((defined('MODULE_PAYMENT_PAYPAL_STATUS') && MODULE_PAYMENT_PAYPAL_STATUS == 'True') OR (defined('MODULE_PAYMENT_PAYPALEXPRESS_STATUS') && MODULE_PAYMENT_PAYPALEXPRESS_STATUS == 'True'))
	$o_paypal = new paypal_checkout();
	
if((defined('MODULE_PAYMENT_PI_CLICKANDBUY_STATUS') && MODULE_PAYMENT_PI_CLICKANDBUY_STATUS == 'True') OR (defined('MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_STATUS') && MODULE_PAYMENT_PI_CLICKANDBUY_RECURRING_STATUS == 'True'))
	$cab = new clickandbuy();

if(!is_object($_SESSION['cart']))
	$_SESSION['cart'] = new cart();

if(!is_object($_SESSION['wish_list']))
	$_SESSION['wish_list'] = new wish_list();

require(DIR_WS_INCLUDES.FILENAME_CART_ACTIONS);

$message_stack = new message_stack();

activate_banners();
expire_banners();

expire_specials();

if(isset($_GET['products_id'])) {
	$actual_products_id = (int)$_GET['products_id'];
	$product = new product($actual_products_id);
}
if(!is_object($product))
	$product = new product();

if (isset($_GET['cPath']))
	$cPath = input_validation($_GET['cPath'], 'cPath', '');

elseif (is_object($product) && !isset($_GET['brand'])) {
	if ($product->isProduct())
		$cPath = get_product_path($actual_products_id);
	else
		$cPath = '';
} else
	$cPath = '';

if (not_null($cPath)) {
	$cPath_array = parse_category_path($cPath);
	$cPath = implode('_', $cPath_array);
	$current_category_id = $cPath_array[(sizeof($cPath_array) - 1)];
} else
	$current_category_id = 0;

$breadcrumb = new breadcrumb();

$breadcrumb->add(HEADER_TITLE_TOP, HTTP_SERVER);
if(DIR_WS_CATALOG !='/')
	$breadcrumb->add(HEADER_TITLE_CATALOG, href_link(FILENAME_DEFAULT));

if (isset($cPath_array)) {
	for ($i = 0, $n = sizeof($cPath_array); $i < $n; $i ++) {
		if (GROUP_CHECK == 'true')
			$group_check = "and c.group_permission_".$_SESSION['customers_status']['customers_status_id']."=1 ";
		
		$categories = $db->db_query("SELECT
										cd.categories_name
									FROM 
										".TABLE_CATEGORIES_DESCRIPTION." cd,
										".TABLE_CATEGORIES." c
									WHERE 
										cd.categories_id = '".$cPath_array[$i]."'
									AND 
										c.categories_id=cd.categories_id
										".$group_check."
									AND 
										cd.language_id='".(int) $_SESSION['languages_id']."'", true);
		if($categories->_numOfRows)
			$breadcrumb->add($categories->fields['categories_name'], href_link(FILENAME_DEFAULT, category_link($cPath_array[$i])));
		else
			break;
	}
	
} elseif (not_null($_GET['brand'])) {
	$brand = $db->db_query("SELECT brand_name FROM ".TABLE_BRAND." WHERE brand_id = '".(int)$_GET['brand']."'");

	$breadcrumb->add($brand->fields['brand_name'], href_link(FILENAME_DEFAULT, brand_link((int)$_GET['brand'], $brand->fields['brand_name'])));
}

if ($product->isProduct()) {
  require_once(DIR_FS_INC.'inc.count_products_in_category.php');
  if (count_products_in_category_by_productid($product->pID) == 1)
    array_pop($breadcrumb->_trail);
	$breadcrumb->add($product->getBreadcrumbModel(), href_link(FILENAME_PRODUCT_INFO, 'products_id='.$product->data['products_id']));
}

define('WARN_INSTALL_EXISTENCE', 'false');
define('WARN_CONFIG_WRITEABLE', 'true');
define('WARN_SESSION_DIRECTORY_NOT_WRITEABLE', 'true');
define('WARN_SESSION_AUTO_START', 'true');
define('WARN_DOWNLOAD_DIRECTORY_NOT_READABLE', 'true');

require(DIR_WS_CLASSES.'Smarty_3.0.7/Smarty.class.php');

if(isset($_SESSION['customer_id'])) {
	$account_type = $db->db_query("SELECT
										account_type,
										customers_default_address_id
									FROM
										".TABLE_CUSTOMERS."
									WHERE
										customers_id = '".(int) $_SESSION['customer_id']."'", true);

	if (!isset($_SESSION['customer_country_id'])) {
		$zone = $db->db_query("SELECT
									entry_country_id
								FROM
									".TABLE_ADDRESS_BOOK."
								WHERE
									customers_id='".(int)$_SESSION['customer_id']."'
								AND
									address_book_id='".$account_type->fields['customers_default_address_id']."'", true);

		$_SESSION['customer_country_id'] = $zone->fields['entry_country_id'];
	}
	$_SESSION['account_type'] = $account_type->fields['account_type'];

} else
	$_SESSION['account_type'] = '0';

$check = basename($_SERVER['PHP_SELF']);
if((DOWN_FOR_MAINTENANCE == 'true') && ($_SESSION['customers_status']['customers_status_id'] != 0) && ($check != FILENAME_DOWN_FOR_MAINTENANCE_LOGIN) && ($check != 'java.js.php') && ($check != 'style.css.php') && ($check != 'mercari_img.php') && ($check != 'captcha.php'))
	redirect(FILENAME_DOWN_FOR_MAINTENANCE_LOGIN);

$browser = new Browser();
get_template();
count_cart();

include_once(DIR_FS_INC.'inc.debug.php');
